<?php
class dbConnect{
	/**
	*数据库连接初始化函数(构造函数)
	**/
	protected $conn;
	function __construct($localhost,$username,$password,$table){
		$this->conn = mysqli_connect($localhost,$username,$password);
		if(!($this->conn)){
			die('Could not connect:' . mysqli_error());
		}else{
			// print "连接成功<br/>";
			mysqli_query($this->conn , "SET NAMES UTF8");
			mysqli_select_db($this->conn , $table);
		}
	}

	/**
	*输出指定表的所有内容
	**/
	function selectAll($table , $limit){
		$sql = "select * from ".$table." LIMIT ".$limit;
		return $this->executeQuery($sql);
	}

	function select($table, $where){
		$sql = "select * from " . $table . " where 1 = 1 ";
		foreach($where as $key=>$value)
		{
			$sql .= " and " . $key . " = '" . $value . "' ";
		}
		// echo $sql;
		return $this->executeQuery($sql);
	}

	function insert($table, $data){
		$sql = 'insert into '. $table;
		$fieldKey = ' ( ';
		$fieldValue = ' (';
		foreach($data as $key=>$value)
		{
			$fieldKey .= $key . ' ,';
			$fieldValue .= "'".$value ."'". " ,";
		}
		$fieldKey = substr($fieldKey,0,strlen($fieldKey)-1) . ') ';
		$fieldValue = substr($fieldValue,0,strlen($fieldValue)-1) . ') ';
		$sql = $sql . $fieldKey . 'value' . $fieldValue;

		// echo $sql;
//		die();
		return $this->updataQuery($sql);

	}

	function update($table, $setting, $where){
		if(empty($setting)){
			return false;
		}
		$sql = "update ".$table." set ";
		foreach($setting as $key => $value){
			$sql .= $key . ' = ' . $value . ' ,';
		}
		$sql = substr($sql,0,strlen($sql)-1);
		$sql .= ' where 1 = 1 ';
		foreach($where as $key => $value){
			$sql .= ' and ' . $key . ' = ' . $value;
		}
//		echo $sql;
//		die();
		return $this->updataQuery($sql);

	}


	/**
	 * 查询指定sql
	 */
	function executeQuery($sql){
		$data = array();
		$result = mysqli_query($this->conn, $sql);
		while ($row = mysqli_fetch_array($result)){
			array_push($data, $row);
		}
		return $data;
	}

	function updataQuery($sql){
		$result = mysqli_query($this->conn, $sql);

		return $result;
	}



	/*
	*析构函数
	*关闭数据库
	*/
   public function __destruct() {
		mysqli_close($this->conn);
	}
}
?>